import java.util.Arrays;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: dings
 * Date: 2024-07-17
 * Time: 16:38
 */
class Solution {
    StringBuilder stringBuilder = new StringBuilder();
    public String tree2str(TreeNode root) {
        tree2strChild(root);
        return stringBuilder.toString();
    }
    public void tree2strChild(TreeNode root) {
        if(root == null) {
            return ;
        }
        stringBuilder.append(root.val);
        if(root.left != null) {
            //左子树不为空，则必然添加"("
            stringBuilder.append("(");
            //递归左子树
            tree2strChild(root.left);
            //该节点左子树完，则拼接")"
            stringBuilder.append(")");
        }else {
            //左子树为空，且右子树为空，直接返回
            if(root.right == null) {
                return;
            }else {
                //左子树为空，但右子树不为空，需拼接"()"
                stringBuilder.append("()");
            }
        }
        //若右孩子为空，则直接返回；若右孩子不为空，则拼接"("并递归右子树
        if (root.right != null) {
            stringBuilder.append("(");
            tree2str(root.right);
            stringBuilder.append(")");
        }else {
            return;
        }
    }
}